package com.zhiyizhen.handheld.common.view.adapter.recyclerview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseAdapter<T, VH extends BaseViewHolder<T>> extends RecyclerView.Adapter<VH> implements View.OnClickListener {

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    protected final Context mContext;
    protected final List<T> mData;
    private OnItemClickListener mOnItemClickListener;

    protected BaseAdapter(Context context) {
        this(context, null);
    }

    protected BaseAdapter(Context context, List<T> data) {
        mContext = context;
        mData = data == null ? new ArrayList<>() : new ArrayList<>(data);
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        holder.itemView.setTag(position);
        holder.bindData(getItem(position), position);
    }

    @Override
    public void onClick(View view) {
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    public T getItem(int position) {
        if (position < 0 || position >= mData.size()) {
            return null;
        }
        return mData.get(position);
    }

    public void setData(List<T> data) {
        mData.clear();
        addAll(data);
    }

    @SuppressLint("NotifyDataSetChanged")
    public void add(T item) {
        mData.add(item);
        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void addAll(List<T> items) {
        if (items != null) {
            mData.addAll(items);
        }
        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void remove(T item) {
        mData.remove(item);
        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void clear() {
        mData.clear();
        notifyDataSetChanged();
    }

    public List<T> getData() {
        return mData;
    }

}
